<!--盘点单-->
<template>
    <el-form :model="checkform" ref="checkref" :inline="true" style="text-align: left;">
        <el-form-item label="盘点单号:" prop="code">
            <el-input placeholder="请输入" v-model="checkform.code"></el-input>
        </el-form-item>
        <el-form-item label="盘点类型" prop="type">
            <el-select placeholder="请选择" style="width:200px" v-model="checkform.type">
                <el-option v-for="item in types" :key="item.bus_id" :label="item.bus_name" :value="item.bus_name"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="盘点结果" prop="status">
            <el-select placeholder="请选择" style="width:200px" v-model="checkform.status">
                <el-option v-for="item in status" :key="item.dict_value" :label="item.dict_label" :value="item.dict_value"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="仓库名称" prop="whid">
            <el-select placeholder="请选择" v-model="checkform.whid" style="width:200px">
                <el-option v-for="item in warehouse" :key="item.wh_id" :label="item.wh_name" :value="item.wh_id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button @click="Reset">重置</el-button>
            <el-button type="success" @click="Search">查询</el-button>
            <el-button @click="AdvancedSearch">高级查询</el-button>
        </el-form-item>
    </el-form>
    <div style="text-align: left;">
        <el-button type="success" @click="ShowAdd">新增</el-button>
        <el-button type="danger" @click="ShowDeleteAll">删除</el-button>
        <el-button @click="Export">导出</el-button>
        <el-button @click="LockWarehouse">锁定仓库</el-button>
        <el-button @click="Refresh">刷新</el-button>
    </div>
    <!--表格-->
    <el-table :data="checkdata" stripe style="margin-top: 10px;" @selection-change="SelectChange">
        <el-table-column fixed type="selection"></el-table-column>
        <el-table-column fixed type="index" label="序号" width="100"></el-table-column>
        <el-table-column fixed label="盘点单号" width="200px">
            <template #default="scope">
                <span style="color: green;cursor: pointer;" @click="ShowInfo(scope.row)">{{ scope.row.ic_code }}</span>
            </template>
        </el-table-column>
        <el-table-column fixed prop="ic_status" label="盘点结果"></el-table-column>
        <el-table-column prop="wh_name" label="仓库名称" width="200px"></el-table-column>
        <el-table-column prop="ic_type" label="盘点类型"></el-table-column>
        <el-table-column prop="start_time" label="盘点开始时间" width="200px"></el-table-column>
        <el-table-column prop="end_time" label="盘点结束时间" width="200px"></el-table-column>
        <el-table-column prop="outstock_status" label="出库状态" width="200px"></el-table-column>
        <el-table-column prop="instock_status" label="入库状态" width="200px"></el-table-column>
        <el-table-column label="盘点货品" width="250">
            <template #default="scope">
                <el-tooltip
                    effect="dark"
                    :content="scope.row.proc_list_full"
                    placement="top"
                    :disabled="!scope.row.proc_list_full || scope.row.proc_list_full.split('、').length <= 3"
                >
                    <span>{{ scope.row.proc_list }}</span>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="check_num" label="盘点数量" width="120px"></el-table-column>
        <el-table-column prop="checkprofit_num" label="盘盈数量" width="120px">
            <template #default="scope">
                <span style="color: #67C23A;">{{ scope.row.checkprofit_num }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="checklosses_num" label="盘亏数量" width="120px">
            <template #default="scope">
                <span style="color: #F56C6C;">{{ scope.row.checklosses_num }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="checkprofit_total" label="盘盈金额" width="120px">
            <template #default="scope">
                <span style="color: #67C23A;">{{ scope.row.checkprofit_total ? Number(scope.row.checkprofit_total).toFixed(2) : '0.00' }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="checklosses_total" label="盘亏金额" width="120px">
            <template #default="scope">
                <span style="color: #F56C6C;">{{ scope.row.checklosses_total ? Number(scope.row.checklosses_total).toFixed(2) : '0.00' }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="ic_user" label="经办人"></el-table-column>
        <el-table-column prop="create_name" label="制单人"></el-table-column>
        <el-table-column prop="create_time" label="制单时间" width="200px"></el-table-column>
        <el-table-column label="操作" fixed="right" width="160px">
            <template #default="scope">
                <el-button 
                    v-if="['草稿'].includes(scope.row.ic_status)"
                    type="success" 
                    text="编辑" @click="ShowUpdate(scope.row)">
                    编辑
                </el-button>
                <el-button 
                    v-if="['草稿'].includes(scope.row.ic_status)"
                    type="danger" 
                    text="删除" @click="ShowDelete(scope.row.ic_id)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 页码 -->
    <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
        v-on:current-change="handlePageChange" style="float:right;margin-top:20px">
    </el-pagination>

    <!--高级搜索-->
    <el-drawer v-model="drawer">
        <template #header>
            <h4 style="text-align: left;">高级查询</h4>
        </template>
        <template #default>
            <el-form label-width="120px" label-position="top" :model="searchform" ref="searchref">
                <el-row :gutter="24">
                    <!-- 左列 -->
                    <el-col :span="12">
                        <el-form-item label="盘点单号" prop=code>
                            <el-input placeholder="请输入" v-model="searchform.code"/>
                        </el-form-item>
                        <el-form-item label="盘点日期" prop="date">
                            <el-date-picker v-model="searchform.date" type="datetimerange" range-separator="To" start-placeholder="Start date" end-placeholder="End date" />
                        </el-form-item>
                        <el-form-item label="盘点结果" prop="status">
                            <el-select placeholder="请选择" v-model="searchform.status">
                                <el-option v-for="item in status" :key="item.dict_value" :label="item.dict_label" :value="item.dict_value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="盘点类型" prop="type">
                            <el-select placeholder="请选择" v-model="searchform.type">
                                <el-option v-for="item in types" :key="item.bus_id" :label="item.bus_name" :value="item.bus_name"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="仓库名称" prop="whid">
                            <el-select placeholder="请选择" v-model="searchform.whid">
                                <el-option v-for="item in warehouse" :key="item.wh_id" :label="item.wh_name" :value="item.wh_id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!-- 右列 -->
                    <el-col :span="12">
                        <el-form-item label="制单人" prop="createname">
                            <el-input placeholder="请输入" v-model="searchform.createname"/>
                        </el-form-item>
                        <el-form-item label="制单时间" prop="createtime">
                            <el-date-picker v-model="searchform.createtime" type="datetimerange" range-separator="To" start-placeholder="Start date" end-placeholder="End date" />
                        </el-form-item>
                        <el-form-item label="审核人" prop="approvername">
                            <el-input placeholder="请输入" v-model="searchform.approvername"/>
                        </el-form-item>
                        <el-form-item label="审核时间" prop="approvertime">
                            <el-date-picker v-model="searchform.approvertime" type="datetimerange" range-separator="To" start-placeholder="Start date" end-placeholder="End date" />
                        </el-form-item>
                        <el-form-item label="经办人" prop="checkuser">
                            <el-input placeholder="请输入" v-model="searchform.checkuser"/>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="AdvancedReset">重置</el-button>
                <el-button @click="drawer = false">关闭</el-button>
                <el-button type="primary" @click="AdvancedOk">确定</el-button>
            </div>
        </template>
    </el-drawer>

    <!--删除模态框-->
    <el-dialog v-model="DeleteialogVisible" width="400" style="text-align: left;" align-center>
        <span>确定删除吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="DeleteialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Delete()">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!--选中删除模态框-->
    <el-dialog v-model="DeleteialogVisible2" width="400" style="text-align: left;" align-center>
        <span>确定删除选中的数据吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="DeleteialogVisible2 = false">取消</el-button>
                <el-button type="primary" @click="DeleteAll()">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!--撤销模态框-->
    <el-dialog v-model="CancelDialogVisible" width="400" style="text-align: left;" align-center>
        <span>确定撤销吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="CancelDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Cancel()">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!--选中撤销模态框-->
    <el-dialog v-model="CancelDialogVisible2" width="400" style="text-align: left;" align-center>
        <span>确定撤销选中的数据吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="CancelDialogVisible2 = false">取消</el-button>
                <el-button type="primary" @click="CancelAll()">确定</el-button>
            </div>
        </template>
    </el-dialog>
    
</template>

<script>
import {ref,reactive,onMounted, computed} from 'vue';
import http from '../auth/index';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';//路由
import * as XLSX from 'xlsx';
export default {
setup() {
    const router = useRouter();
    const user = JSON.parse(sessionStorage.getItem("user"));
    function formatDateTime(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    //转换盘点货品
    function formatGoodsList(goods) {
        if (!goods) return "";
        const goodsArray = Array.isArray(goods) ? goods : goods.split('、').filter(Boolean);
        if (goodsArray.length <= 3) {
            return goodsArray.join('、');
        } else {
            const firstThree = goodsArray.slice(0, 3).join('、');
            return `${firstThree}等${goodsArray.length}项....`;
        }
    }
    // 盘点类型
    const types = ref([]);
    function GetTypes() {
        return http.get("/BusinessType/GetBusinessTypes?field=盘点")
        .then(res => {
            types.value = res.data;
        }).catch(err => {
            console.log(err);
        })
    }
    // 单据状态
    const status = ref([]);
    function GetStatus() {
        return http.get("/DictData/GetAllDictDataBytype?typeid=7")
        .then(res => {
            status.value = res.data;
        }).catch(err => {
            console.log(err);
        })
    }

     // 出入库单据状态
    const status2 = ref([]);
    function GetStatus2() {
        return http.get("/DictData/GetAllDictDataBytype?typeid=6")
        .then(res => {
            status2.value = res.data;
        }).catch(err => {
            console.log(err);
        })
    }

     //查询所有仓库
    const warehouse=ref([]);
    function AllWarehouse(){
        http.get("/Warehouse/GetWarehouses")
        .then(res=>{
                warehouse.value=res.data;
        }).catch(err=>{
                console.log(err);
        })
    }

    // 选中数据
    const selectdata = ref([]);
    function SelectChange(val) {
        selectdata.value = val;
    }
    // 导出
    function Export() {
        if (selectdata.value.length == 0) {
            ElMessage({ message: '请选择要导出的数据.', type: 'warning', });
            return;
        }
        const wb = XLSX.utils.book_new();
        const excelData = selectdata.value.map((row) => ({
            '盘点单号': row.ic_code,
            '盘点结果': row.ic_status,
            '仓库名称': row.wh_name,
            '盘点类型': row.ic_type,
            '盘点开始时间': row.start_time,
            '盘点结束时间': row.end_time,
            '出库状态': row.outstock_status,
            '入库状态': row.instock_status,
            '盘点货品': row.proc_list || '',
            '盘点数量': row.check_num,
            '盘盈数量': row.checkprofit_num,
            '盘亏数量': row.checklosses_num,
            '盘盈金额': row.checkprofit_total ? Number(row.checkprofit_total).toFixed(2) : '0.00',
            '盘亏金额': row.checklosses_total ? Number(row.checklosses_total).toFixed(2) : '0.00',
            '经办人': row.ic_user,
            '制单人': row.create_name,
            '制单时间': row.create_time
        }));
        const ws = XLSX.utils.json_to_sheet(excelData);
        XLSX.utils.book_append_sheet(wb, ws, "盘点单");
        XLSX.writeFile(wb, `盘点单${new Date().toLocaleDateString()}.xlsx`);
    }
    
    //当前选中的id
    const checkid = ref("");

    //刷新
    function Refresh() {
        All();
    }
    

    //#region 查询
    const checkref = ref("");
    const checkform = reactive({
        code: "",
        type: "",
        status: "",
        whid: ""
    });
    //重置
    function Reset() {
        checkref.value?.resetFields();
        All();
    }
    const checkdata = ref([]);
    const rows = ref(0);
    const currentPage = ref(1);
    const dateFormat = 'YYYY-MM-DD HH:mm:ss';
    //盘点结果
    const statusMap = computed(() => {
        const map = {};
        if (status.value && status.value.length > 0) {
            status.value.forEach(item => {
                map[item.dict_value] = item.dict_label;
            });
        }
        return map;
    });

    //出入库状态
    const statusMap2 = computed(() => {
        const map = {};
        if (status2.value && status2.value.length > 0) {
            status2.value.forEach(item => {
                map[item.dict_value] = item.dict_label;
            });
        }
        return map;
    });
    //查询
    function Search() {
        All();
    }
    function All() {
        http.get("/Check_h/GetCheck_h", {
            params: {
                code: checkform.code,
                type: checkform.type,
                status: checkform.status,
                whid: checkform.whid,
                CurrentPage: currentPage.value
            }
        }).then(res => {
            rows.value = res.data.rows;
            if (res.data.list.length == 0) {
                ElMessage({ message: '没有相关数据.', type: 'warning', })
            }
            const Data = res.data.list.map(item => ({
                ...item,
                start_time: formatDateTime(new Date(item.start_time)),
                end_time: formatDateTime(new Date(item.end_time)),
                create_time: formatDateTime(new Date(item.create_time)),
                approver_time: item.approver_time ? formatDateTime(new Date(item.approver_time)) : "",
                proc_list_full: item.proc_list,
                proc_list: formatGoodsList(item.proc_list),
                ic_status: statusMap.value[item.ic_status] || "未知状态",
                outstock_status: statusMap2.value[item.outstock_status] || "未知状态",
                instock_status: statusMap2.value[item.instock_status] || "未知状态",
            }));
            Data.sort((a, b) => new Date(b.create_time) - new Date(a.create_time));
            checkdata.value = Data;
        }).catch(err => {
            console.log(err)
        })
    }
    function handlePageChange(page) {
        currentPage.value = page;
        All();
    }
    //#endregion
    

    //#region 高级查询
    const drawer = ref(false);
    function AdvancedSearch() {
        drawer.value = true;
    }
    const searchref = ref("");
    const searchform = reactive({
        code: "",
        date: [null, null],
        status: "",
        type: "",
        whid: "",
        createname: "",
        createtime: [null, null],
        approvername: "",
        approvertime: [null, null],
        checkuser: ""
    });
    //重置
    function AdvancedReset() {
        searchref.value?.resetFields();
    }
    function AdvancedOk() {
        http.get("/Check_h/GetAdvancedCheck_h", {
            params: {
                code: searchform.code,
                startdate: searchform.date[0],
                enddate: searchform.date[1],
                status: searchform.status,
                type: searchform.type,
                whid: searchform.whid,
                createname: searchform.createname,
                startcreatetime: searchform.createtime[0],
                endcreatetime: searchform.createtime[1],
                approvername: searchform.approvername,
                startapprovertime: searchform.approvertime[0],
                endapprovertime: searchform.approvertime[1],
                checkuser: searchform.checkuser,
                CurrentPage: currentPage.value
            }
        }).then(res => {
            rows.value = res.data.rows;
            if (res.data.list.length == 0) {
                ElMessage({ message: '没有相关数据.', type: 'warning', })
            }
            const Data = res.data.list.map(item => ({
                ...item,
                start_time: formatDateTime(new Date(item.start_time)),
                end_time: formatDateTime(new Date(item.end_time)),
                create_time: formatDateTime(new Date(item.create_time)),
                approver_time: item.approver_time ? formatDateTime(new Date(item.approver_time)) : "",
                proc_list_full: item.proc_list,
                proc_list: formatGoodsList(item.proc_list),
                ic_status: statusMap.value[item.ic_status] || "未知状态",
                outstock_status: statusMap2.value[item.outstock_status] || "未知状态",
                instock_status: statusMap2.value[item.instock_status] || "未知状态",
            }));
            checkdata.value = Data;
        }).catch(err => {
            console.log(err)
        })
    }

    //#endregion
    
    //#region 跳转新增页面
    function ShowAdd() {
        router.push("checkadd");
    }
    //#endregion


    //#region 删除
    // 删除
    const DeleteialogVisible = ref(false);
    function ShowDelete(id) {
        checkid.value = id;
        DeleteialogVisible.value = true;
    }
    async function Delete() {
        try {
            // 直接调用删除接口
            const deleteRes = await http.put("/Check_h/DeleteCheck_h?id=" + checkid.value);
            if (deleteRes.data > 0) {
                ElMessage({ message: '删除成功.', type: 'success' });
                All();
                DeleteialogVisible.value = false;
            } else {
                ElMessage.error('删除失败.');
            }
        } catch (err) {
            console.error("删除失败:", err);
            ElMessage.error('删除操作失败.');
        }
    }
    const DeleteialogVisible2 = ref(false);
    function ShowDeleteAll() {
        if (selectdata.value.length == 0) {
            ElMessage({ message: '请选择要删除的数据.', type: 'warning', });
            return;
        }
        const invalidItems = selectdata.value.filter(item => !['草稿', '待审核'].includes(item.check_status));
        if (invalidItems.length > 0) {
            ElMessage({ message: '选中的单据中包含不可删除的状态(只有草稿或待审核状态可删除)', type: 'warning', });
            return;
        }
        DeleteialogVisible2.value = true;
    }
    async function DeleteAll() {
        try {
            const deletePromises = selectdata.value.map(row =>
                http.put("/Check_h/DeleteCheck_h?id=" + row.check_id)
            );
            
            // 并行执行所有删除请求
            await Promise.all(deletePromises);

            ElMessage({ message: '选中单据已成功删除.', type: 'success' });
            All();
            DeleteialogVisible2.value = false;
        } catch (err) {
            console.error("批量删除失败:", err);
            ElMessage.error('批量删除操作失败.');
        }
    }
    //#endregion


    //#region 跳转修改页面
    function ShowUpdate(row) {
        router.push({ name: "checkupdate", params: { checkid: row.ic_id, checkcode: row.ic_code } });
    }
    //#endregion

    // 审核
    const AuditDialogVisible = ref(false);
    const auditResult = ref("");
    const auditComment = ref("");
    function ShowAudit() {
        if (selectdata.value.length == 0) {
            ElMessage({ message: '请选择要审核的单据.', type: 'warning', })
            return;
        }
        const validItems = selectdata.value.filter(item => item.check_status === "待审核");
        if (validItems.length == 0) {
            ElMessage({ message: '选中的单据中没有可审核的单据(只有待审核状态可审核)', type: 'warning', })
            return;
        }
        AuditDialogVisible.value = true;
    }
    function Audit() {
        selectdata.value.forEach(item => {
            if (item.check_status === "待审核") {
                http.put("/Check_h/ApproverCheck_h?checkid=" + item.check_id + "&status=" + auditResult.value + "&approvername=" + user.name + "&approvertime=" + formatDateTime(new Date()))
                .then(res => {
                    if (res.data > 0) {
                        ElMessage({ message: '审核成功.盘点成功.', type: 'success', })
                        All();
                        AuditDialogVisible.value = false;
                    } else {
                        ElMessage.error('审核失败.')
                    }
                }).catch(err => {
                    console.log(err);
                })
            }
        })
    }
    //#endregion

    //#region 查看详情
    function ShowInfo(row) {
        router.push({ name: "checkinfo", params: { checkid: row.ic_id, checkcode: row.ic_code } });
    }
    //#endregion


    //锁定仓库
    function LockWarehouse() {
        //跳转仓库页面
        router.push("warehouse");
    }

    //挂载
    onMounted(() => {
        GetTypes();
        GetStatus2();
        GetStatus().then(() => {
            All();
        });
        AllWarehouse();
    });


    return {
        AdvancedSearch,
        drawer,
        status,
        types,
        warehouse,
        checkref,
        checkform,
        Reset,
        checkdata,
        rows,
        currentPage,
        dateFormat,
        handlePageChange,
        Search,
        searchform,
        searchref,
        AdvancedReset,
        AdvancedOk,
        ShowAdd,
        selectdata,
        SelectChange,
        Export,
        DeleteialogVisible,
        ShowDelete,
        Delete,
        checkid,
        DeleteAll,
        DeleteialogVisible2,
        ShowDeleteAll,
        ShowUpdate,
        Refresh,
        ShowInfo,
        LockWarehouse
    }
}
}
</script>

<style scoped>
</style>